package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate l : dateList){
            LocalDateTime beginTime=LocalDateTime.of(l, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(l, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover=orderMapper.sumByMap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        String join = StringUtils.join(dateList, ",");
        String joinTurnover = StringUtils.join(turnoverList, ",");
        TurnoverReportVO turnoverReportVO=new TurnoverReportVO();
        turnoverReportVO.setDateList(join);
        turnoverReportVO.setTurnoverList(joinTurnover);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> allUserList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate l : dateList){
            LocalDateTime beginTime=LocalDateTime.of(l, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(l, LocalTime.MAX);
            Map map=new HashMap<>();

            map.put("end",endTime);
            Integer allUser=userMapper.newusersumBymap(map);
            map.put("begin",beginTime);
            Integer newUser=userMapper.newusersumBymap(map);
            newUser=newUser==null?0:newUser;
            allUser=allUser==null?0:allUser;
            newUserList.add(newUser);
            allUserList.add(allUser);
        }
        String join = StringUtils.join(dateList, ",");
        String newUsers = StringUtils.join(newUserList, ",");
        String allUsers = StringUtils.join(allUserList, ",");
        UserReportVO vo=new UserReportVO();
        vo.setDateList(join);
        vo.setNewUserList(newUsers);
        vo.setTotalUserList(allUsers);
        return vo;
    }

    @Override
    public OrderReportVO getorderReportStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer> orderList=new ArrayList<>();
        List<Integer> useOrderList=new ArrayList<>();
        dateList.add(begin);
        Integer total=0;
        Integer Usertotal=0;
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate l : dateList){
            LocalDateTime beginTime=LocalDateTime.of(l, LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(l, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer allOrder=orderMapper.ordersumBymap(map);
            total=total+allOrder;
            map.put("status",Orders.COMPLETED);
            Integer useOrder=orderMapper.ordersumBymap(map);
            Usertotal=Usertotal+useOrder;
            orderList.add(allOrder);
            useOrderList.add(useOrder);

    }
        String date = StringUtils.join(dateList, ",");
        String order = StringUtils.join(orderList, ",");
        String useorder = StringUtils.join(useOrderList, ",");
        OrderReportVO vo=new OrderReportVO();
        vo.setDateList(date);
        vo.setOrderCountList(order);
        vo.setValidOrderCountList(useorder);
        vo.setTotalOrderCount(total);
        vo.setValidOrderCount(Usertotal);
        if(total!=0){
            Double ration=Usertotal.doubleValue()/total;
            vo.setOrderCompletionRate(ration);
        }
        return vo;
    }

    @Override
    public SalesTop10ReportVO getsalesStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> top=orderMapper.top10(begin,end);
        List<String> names = top.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> number = top.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(number, ",");
        SalesTop10ReportVO salesTop10ReportVO=new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameList);
        salesTop10ReportVO.setNumberList(numberList);
        return salesTop10ReportVO;
    }

    @Override
//    导出数据
    public void export(HttpServletResponse response) throws IOException {
//        1.准备数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
//        通过POI写入excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间"+begin+"至"+end);
            sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
//            明细数据
            for (int i =0;i<30;i++){
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            outputStream.close();
            excel.close();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
